package com.lucky.common.utils;

import com.lucky.blog.controller.HomeController;
import com.lucky.common.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @version 1.0
 * @Author: chancy
 * @date: 2020/9/21 14:13
 */
public class CallCmd {

    private final static Logger log = LoggerFactory.getLogger(CallCmd.class);

    public static void  exec(String batPath){
        exec(batPath, null);
    }

    public static void  exec(String batPath, String prefix){
        File batFile = new File(batPath);
        boolean batFileExist = batFile.exists();
        if (!batFileExist) {
            log.error("脚本不存在");
            throw new SystemException("脚本不存在");
        }
        StringBuilder sb = new StringBuilder();
        InputStream in = null;
        BufferedReader bufferedReader = null;
        try {
            if(prefix != null){
                batPath = prefix + batPath;
            }
            Process child = Runtime.getRuntime().exec(batPath);
            in = child.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            in.close();
            child.waitFor();
            log.info("callCmd :\n" + sb.toString());
        } catch (IOException | InterruptedException e) {
            log.info("脚本执行失败：{}", e.getMessage());
        }finally {
            try {
                assert in != null;
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                assert bufferedReader != null;
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
